package examples3;

import net.corda.core.contracts.Command;
import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.contracts.ContractState;
import net.corda.core.identity.Party;
import net.corda.core.transactions.LedgerTransaction;
import org.jetbrains.annotations.NotNull;

import java.security.PublicKey;
import java.util.List;

//import java.rmi.registry.Registry;


public class HouseContract implements Contract {


    @Override
    public void verify(@NotNull LedgerTransaction tx) throws IllegalArgumentException {
        if (tx.getCommands().size() != 1) {
            throw new IllegalArgumentException("Transaction must have one command! ");
        }
        Command command  = tx.getCommand(0);
        CommandData commandType = tx.getCommand(0).getValue();
        // 对每一个command进行分类验证
        if (commandType instanceof Register) {

            //shape（state和command的输入和输出限制）
            if(tx.getInputStates().size()!=0){
                throw new IllegalArgumentException("Register transaction must have zero input !");
            }if(tx.getOutputStates().size()!=1){
                throw new IllegalArgumentException("Register transaction must have one output ! ");
            }
            //具体的业务逻辑（自己定义）
            ContractState outputState = tx.getOutput(0);
            if(!(outputState instanceof HouseState)){
                throw new IllegalArgumentException("Output must be a HouseState !");
            }
            HouseState houseState = (HouseState) outputState;
            if(houseState.getAddress().length()<3){
                throw new IllegalArgumentException("Address must be more than 3 characters !");
            }if(!houseState.getOwner().getName().getCountry().equals("CN")){
                throw new IllegalArgumentException("Owner of the house must be in China !");
            }

            //需要各方拥有者的签名（可以一方或者多方，需要按业务逻辑定义）
            List<PublicKey> requiredKeys = command.getSigners();
//            PublicKey issuerKey = iouState.getIssur().getOwningKey();
            Party owner = houseState.getOwner();
            PublicKey ownerKey = owner.getOwningKey();
            if(!(requiredKeys.contains(ownerKey))){
                throw new IllegalArgumentException("Issuer must a required signer !");
            }
        }else if(commandType instanceof Transfer) {

        }else{
            throw new IllegalArgumentException("Unrecognized command !");
        }
    }

    /**
     * 具体要实现的动作，每个动作过程都不同，参与的人都不同，需要签名的人都不同
     */
    public class Register implements CommandData{};
    public class Transfer implements CommandData{};
}
